package com.ftt;

import com.google.gson.Gson;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/product_list.do")
public class ProductListServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Connection conn = DBUtile.getConnection();
        String sql ="select * from tb_product order by create_time desc limit 10";
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {

            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ArrayList list = new ArrayList();
            while (rs.next()) {
               Product p = new Product();
                p.setId( rs.getInt("id"));
                p.setName(rs.getString("name"));
                p.setDescription(rs.getString("description"));
                p.setMarket_price((float) rs.getDouble("market_price"));
                p.setSell_price((float) rs.getDouble("sell_price"));
                p.setPicture(rs.getString("picture"));

            list.add(p);
            p=null;
            }
            //返回数据
            resp.setContentType("application/json;charset=utf-8");
           Gson gson = new Gson();
           String result = gson.toJson(list);

            resp.getWriter().println(result);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtile.closeResource(conn, ps, rs);
        }

//        req.getRequestDispatcher("/product_list.jsp").forward(req, resp);
    }
}
